package com.piggy.logi.common.datascope.service;

import com.piggy.common.core.constant.BizConstants;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.core.utils.FeignResultUtils;
import com.piggy.common.core.utils.StringUtils;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.logi.sys.api.RemoteLogiUserService;
import com.piggy.logi.sys.api.domain.LogiSysUser;
import com.piggy.common.core.domain.R;
import com.piggy.sys.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 同步调用用户服务
 *
 * @author ruoyi
 */
@Service
public class LogiAwaitUserService
{
    private static final Logger log = LoggerFactory.getLogger(LogiAwaitUserService.class);

    @Resource
    private RemoteLogiUserService remoteUserService;

    /**
     * 查询当前用户信息
     *
     * @return 用户基本信息
     */
    public LoginUser<LogiSysUser> info()
    {
        if (!SecurityUtils.getOauthUser().getBiz().equals(BizConstants.LOGI)) {
            return null;
        }
        //String username = SecurityUtils.getUsername();
        LoginUser<LogiSysUser> loginUser = SecurityUtils.getOauthUser();
        R<LoginUser<LogiSysUser>> userResult = null;

        if (StringUtils.isNotBlank(loginUser.getSysUser().getPhonenumber())) {
            userResult = remoteUserService.getUserByPhoneByDept(loginUser.getSysUser().getPhonenumber(), loginUser.getSysUser().getDeptId()+"", SecurityConstants.INNER);
            FeignResultUtils.throwIfFailed(userResult);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
            {
                log.info("数据权限范围查询用户：{}|{}|{} 不存在.", loginUser.getSysUser().getUserName(), loginUser.getSysUser().getPhonenumber(), loginUser.getSysUser().getEmail());
                return null;
            }
            return userResult.getData();
        }

        if (StringUtils.isNotBlank(loginUser.getSysUser().getEmail())) {
            userResult = remoteUserService.getUserByEmailByDept(loginUser.getSysUser().getEmail(), loginUser.getSysUser().getDeptId()+"", SecurityConstants.INNER);
            FeignResultUtils.throwIfFailed(userResult);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
            {
                log.info("数据权限范围查询用户：{}|{}|{} 不存在.", loginUser.getSysUser().getUserName(), loginUser.getSysUser().getPhonenumber(), loginUser.getSysUser().getEmail());
                return null;
            }
            return userResult.getData();
        }

        return null;
    }
}
